/**
 * webSocket 工具类
 */

/**
 * websocket 连接对象
 * @type {WebSocket}
 */
let webSocket = null;
/**
 * 发送定时单位
 */
let setIntervalWebSocketPush = null;

/**
 * 建立连接
 * @param WSS_URL 连接url
 */
export function createSocket(WSS_URL) {
    if (webSocket) {
        console.log('websocket已连接')
    } else {
        console.log('连接websocket');
        webSocket = new WebSocket(WSS_URL);
        webSocket.onopen = onopenWS;
        webSocket.onmessage = onmessageWS;
        webSocket.onerror = onerrorWS;
        webSocket.onclose = oncloseWS;
    }
}

/**
 * 打开WS之后发送心跳
 */
export function onopenWS() {
    sendPing();
}

/**
 * 连接失败重连
 */
export function onerrorWS() {
    clearInterval(setIntervalWebSocketPush);
    webSocket.close();
    //重连
    createSocket();
}

/**
 * WS数据接收统一处理
 * @param event 接收到的消息事件
 */
export function onmessageWS(event) {
    //自定义事件
    window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
            messageEvent: event
        }
    }))
}

/**
 * 发送数据
 * @param type 类型
 * @param eventTypeArr 数据
 */
export function sendWSPush(type, eventTypeArr) {
    const obj = {
        appId: 'base',
        type: type,
        cover: 0,
        event: eventTypeArr
    };
    if (webSocket !== null && webSocket.readyState === 3) {
        webSocket.close();
        createSocket(); //重连
    } else if (webSocket.readyState === 1) {
        webSocket.send(JSON.stringify(obj));
    } else if (webSocket.readyState === 0) {
        setTimeout(() => {
            webSocket.send(JSON.stringify(obj));
        }, 3000)
    }
}

/**
 * 关闭WS
 */
export function oncloseWS() {
    clearInterval(setIntervalWebSocketPush);
    console.log('websocket已断开');
}

/**
 * 发送心跳
 */
export function sendPing() {
    webSocket.send('ping');
    setIntervalWebSocketPush = setInterval(() => {
        webSocket.send('ping');
    }, 5000);
}